$("#activityId").val(parent.seeActivityId);

var locations = [];

// 初始化活动区域
$.ajax({
    url: root.promotion.search_activity_location,
    cache: false,  //禁用缓存
    type: "POST",
    // 告诉jQuery不要去处理发送的数据
    processData: false,
    // 告诉jQuery不要去设置Content-Type请求头
    contentType: false,
    data: {},
    success: function (data) {
        if (data != null && data.errorCode == 0) {
            locations = data.data;
            /*  for (let i = 0; i < data.data.length; i++) {
                  const obj = data.data[i];
                  $("#activityLocation").append("<option value=" + obj.id + ">" + obj.warehouse_name + "</option>");
              }*/
        } else {
            layer.msg('活动区域初始化失败', {
                icon: 2,
                time: 3000
            });
        }
    },
    error: function () {
        console.log("!!!!活动区域初始化失败!!!!");
        layer.msg('活动区域初始化失败', {
            icon: 2,
            time: 3000
        });
    }
});


// 表单重置
function resetData() {
    //$("#activityId").val(parent.seeActivityId);
    $('#promotion_see')[0].reset();
    $("#activityId").val(parent.seeActivityId);
}

// 导出excel
if (parent.seeActivityType == 10) {
    $('#exportProduct').attr('href', root.promotion.export_single_products_by_activityId + '?activityId=' + parent.seeActivityId);
} else {
    $('#exportProduct').attr('href', root.promotion.export_reduce_products_by_activityId + '?activityId=' + parent.seeActivityId);
}

// 默认隐藏满减设置div
$("#reduce_show").css('display', 'none');

// 填充表单头数据
var isFillForm = false;

function fillForm(formData, reduceList) {
    if (isFillForm) {
        return;
    }
    $("#activityName").html(formData.activityName);
    $("#startTime").html(formData.startTime);
    $("#endTime").html(formData.endTime == "" ? "不限" : formData.endTime);
    if (formData.activityPerson == 10) {
        $("#activityPerson").html("普通客户");
    } else if (formData.activityPerson == 20) {
        $("#activityPerson").html("签约客户（非分销)");
    } else if (formData.activityPerson == 30) {
        $("#activityPerson").html("签约客户（分销)");
    }

    $("#activityLocation").html(selectLocationName(formData.activityLocation) == "" ? formData.activityLocation : selectLocationName(formData.activityLocation));

    if (formData.platform == 10) {
        $("#platform").html('不限平台');
    } else if (formData.platform == 20) {
        $("#platform").html('PC端');
    } else if (formData.platform == 30) {
        $("#platform").html('app端');
    }
    var payways = "";
    var ways = formData.payWay.split(",");
    if (ways[0] == "9999") {
        payways += " 不限 ";
    } else {
        for (let i = 0; i < ways.length; i++) {
            const argument = ways[i];
            switch (argument) {
                case "9999":
                    payways += " 不限 ";
                    break;
                case "1001":
                    payways += " 在线支付 ";
                    break;
                case "1301":
                    payways += " 线下汇款 ";
                    break;
                case "1401":
                    payways += " 银行汇票 ";
                    break;
                case "1101":
                    payways += " 货到付款 ";
                    break;
                case "1201":
                    payways += " 账期支付 ";
                    break;
                case "1701":
                    payways += " 门店付款 ";
                    break;
                default:
                    break;
            }
        }
    }
    if (formData.activityPerson == 20 || formData.activityPerson == 30) {
        $("#categoryDiscount_show").show();
        var html = "";
        if (formData.enableCategoryDiscount == 10) {
            html += " 参与 ";

            if (formData.categoryDiscountRule != 10) {
                html += " 品类折扣率 :"
                if (formData.categoryDiscountRule == 20) {
                    html += " 大于等于(>=) "
                } else if (formData.categoryDiscountRule == 30) {
                    html += " 小于(<) "
                }
                html += formData.categoryDiscount + " % 的商品不参与"
            } else {
                html += " 品类折扣率 : 无限制";
            }
        } else {
            html += " 不参与 "
        }
        $("#enableCategoryDiscount").html(html);
    } else {
        $("#categoryDiscount_show").hide();
    }

    $("#payWay").html(payways);
    $("#advertisingWords").html(formData.advertisingWords);
    $("#adPcUrl").html(formData.adPcUrl);
    $("#adAppUrl").html(formData.adAppUrl);
    $("#activityUrl").val(formData.activityUrl);

    if (parent.seeActivityType == 20) {
        $("#navBar").html("满减促销详情");
        $("#reduce_show").css('display', 'inline');
        if (reduceList.length > 0) {
            $("#fullReductionWay").html(reduceList[0].fullReductionWay == 10 ? '满金额优惠' : '满数量优惠');
            $("#fixGrade-10").html(reduceList[0].fullReductionWay == 10 ? '每满固定金额进行优惠' : '每满固定数量进行优惠');
            $("#fixGrade-20").html(reduceList[0].fullReductionWay == 10 ? '满不同级的固定金额进行优惠' : '满不同级的固定数量进行优惠');
            $("#fixGrade-" + reduceList[0].fixGrade).show();
            var unit = reduceList[0].fullReductionWay == 10 ? '元' : '件';
            for (let i = 0; i < reduceList.length; i++) {
                const element = reduceList[i];
                if (element.fixGrade == 10) {
                    $("#useCondition-" + reduceList[0].fullReductionWay).html('每满 ' + element.useCondition + unit);
                    if (element.ruleType == 10) {
                        $("#ruleValue").html('打 ' + element.ruleValue + '折');
                    } else {
                        $("#ruleValue").html('减金额 ' + element.ruleValue + '元');
                    }

                    if (element.preferentialMost == 0) {
                        $("#preferentialMost").html("上不封顶");
                    } else {
                        $("#preferentialMost").html("最多优惠 " + element.preferentialMost + " 元");
                    }
                } else {
                    $("#reduceLevel").show();
                    var ruleValue;
                    if (element.ruleType == 10) {
                        ruleValue = '打 ' + element.ruleValue + '折';
                    } else {
                        ruleValue = '减金额 ' + element.ruleValue + '元';
                    }
                    $("#reduceLevel").append('<tr class="text-c">\n' +
                        '                        <th style="border-right:none">' + element.gradeLevel + '</th>\n' +
                        '                        <th style="border-right:none">' + '满 ' + element.useCondition + unit + '</th>\n' +
                        '                        <th style="border-right:none">' + ruleValue + '</th>\n' +
                        '                    </tr>');
                }
            }
        }
    }
    isFillForm = true;
}

//
// 查询操作
$("#promotion_see").validate({
    submitHandler: function (from) {
        $(from).ajaxSubmit({
            type: 'get',
            url: root.promotion.search_activityDetail_by_activityId_page,
            success: function (data) {
                if (data.errorCode == 0) {
                    fillForm(data.data.result[0].activityBase, data.data.result[0].activityFullReductionList);
                    initTabls(data.data.result[0].activityProductList);
                    $('.M-box3').pagination({
                        pageCount: data.data.totalPage,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            $("#pageNum").val(api.getCurrent());
                            $(from).ajaxSubmit({
                                type: 'get',
                                url: root.promotion.search_activityDetail_by_activityId_page,
                                success: function (data) {
                                    if (data.errorCode == 0) {
                                        initTabls(data.data.result[0].activityProductList);
                                    } else {
                                        layer.msg(data.sub_msg, {
                                            icon: 5,
                                            time: 3000
                                        });
                                    }
                                },
                                error: function (XmlHttpRequest, textStatus, errorThrown) {
                                    console.log(XmlHttpRequest);
                                    console.log(textStatus);
                                    console.log(errorThrown);
                                    layer.msg('促销服务异常,请联系飞岳!', {
                                        icon: 5,
                                        time: 3000
                                    });
                                }
                            });
                        }
                    });

                } else {
                    layer.msg(data.sub_msg, {
                        icon: 5,
                        time: 3000
                    });
                }
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {
                console.log(XmlHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
                layer.msg('促销服务异常,请联系飞岳!', {
                    icon: 5,
                    time: 3000
                });
            }
        });
    }
});
$("#searchButton").click();


// 渲染table
function initTabls(data) {
    console.log(data);
    var dttable = $('#promotion_see_table-10').dataTable(); // 初始化dataTable，清空上一个值
    var dttable2 = $('#promotion_see_table-20').dataTable();
    if (dttable) {
        dttable.fnDestroy(); //还原初始化了的datatable
        dttable.fnClearTable(); //清空一下table
    }
    if (dttable2) {
        dttable2.fnDestroy(); //还原初始化了的datatable
        dttable2.fnClearTable(); //清空一下table
    }
    if (parent.seeActivityType == 10) {
        initSigleTable(data);
    } else {
        initReduceTable(data);
    }

}

$("#promotion_see_table-20").hide();
$("#promotion_see_table-10").hide();

// 渲染单品table
function initSigleTable(data) {
    $("#promotion_see_table-10").show();
    $("#promotion_see_table-10").DataTable({
        "autoWidth": false, // 自动宽度
        "ordering": false, // 开启排序
        "searching": false, //
        "paging": false,
        "serverSide": false, //启用服务器端分页
        "pagingType": "simple_numbers",
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": false,
        "bLengthChange": false,
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='../../static/h-ui.admin/images/loading.gif' />",
        },
        "data": data,
        "columns": [
            {
                "data": "spuCode"
            },
            {
                "data": "spuName"
            },
            {
                "data": "productCode"
            },
            {
                "data": "formName"
            },
            {
                "data": "unitOfMeasurement"
            },
            {
                "data": "costPrice"
            },
            {
                "data": "realTradePrice"
            },
            {
                "data": "retailPrice"
            },
            {
                "data": "ruleType",
                render: function (data, type, row) {
                    var type;
                    var dw;
                    var value;
                    var lsesCont = '';
                    if (data == 10) {
                        type = "折扣";
                        dw = "折";
                        value = Math.round((row.tradePrice * (row.ruleValue / 10)) * 100) / 100;
                        if (value < row.costPrice) {
                            lsesCont = '<span style="font-size: 30%;color: red">小于成本价</span>';
                        }
                    } else {
                        type = "减现金";
                        dw = "元";
                        value = Math.round((row.tradePrice - row.ruleValue) * 100) / 100;
                        if (value < row.costPrice) {
                            lsesCont = '<span style="font-size: 30%;color: red">小于成本价</span>';
                        }
                    }
                    return type + "     " + row.ruleValue + "  " + dw + "   =  " + value + lsesCont;
                }
            },
            {
                "data": "limitNum",
                render: function (data, type, row) {
                    if (row.actualStock < data) {
                        return data + '<span style="font-size: 30%;color: red">存在超卖</span>';
                    }
                    return data == 0 ? "" : data;
                }
            }
        ]
    });
}


// 渲染满减table
function initReduceTable(data) {
    $("#promotion_see_table-20").show()
    $("#promotion_see_table-20").DataTable({
        "autoWidth": false, // 自动宽度
        "ordering": false, // 开启排序
        "searching": false, //
        "paging": false,
        "serverSide": false, //启用服务器端分页
        "pagingType": "simple_numbers",
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": false,
        "bLengthChange": false,
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='../../static/h-ui.admin/images/loading.gif' />",
        },
        "data": data,
        "columns": [
            {
                "data": "spuCode"
            },
            {
                "data": "spuName"
            },
            {
                "data": "productCode"
            },
            {
                "data": "formName"
            },
            {
                "data": "unitOfMeasurement"
            },
            {
                "data": "costPrice"
            },
            {
                "data": "realTradePrice",
                render: function (data, type, row) {
                    if (data < row.costPrice) {
                        return data + '<span style="font-size: 30%;color: red">小于成本价</span>';
                    }
                    return data;
                }
            },
            {
                "data": "retailPrice"
            },
        ]
    });
}

// 获取活动区域
function selectLocationName(id) {
    if (locations.length > 0) {
        for (let i = 0; i < locations.length; i++) {
            const lo = locations[i];
            if (id == lo.id) {
                return lo.warehouse_name;
            }
        }
    }
    return "";
}

function copyActivityUrl() {
    var Url = document.getElementById("activityUrl");
    Url.select(); // 选择对象
    document.execCommand("Copy"); // 执行浏览器复制命令
    layer.msg('复制成功！', {icon: 6, time: 1000});

}